<template>
  <view class="flex-col page login-page">
    <view class="flex-col justify-start items-end self-center image-wrapper">
      <image class="image_2" mode="widthFix" :src="imgUrl + 'WechatIMG136@2x.png'" />
    </view>
    <view class="flex-col self-stretch group">
      <!-- <button class="mt-24 flex-col justify-start items-center text-wrapper w-full" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber"> -->
      <!-- <button class="mt-24 flex-col justify-start items-center text-wrapper w-full" open-type="chooseAvatar"
        @click="getUserProfileByWx" @chooseavatar="onChooseavatar" v-if="!showPhoneBtn">
        <text class="text">微信一键登录</text>
      </button> -->
      <!-- 手机号获取按钮 -->
      <!-- <button v-if="showPhoneBtn" class="mt-24 flex-col justify-start items-center text-wrapper w-full"
        open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
        <text class="text">获取手机号</text>
      </button> -->
      <!-- <button class="mt-24 flex-col justify-start items-center text-wrapper w-full" @click="getUserProfileByWx"
        open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
        <text class="text">微信一键登录</text>
      </button> -->
      <!-- 第一步：选择头像 + 授权资料 -->
      <button class="mt-24 flex-col justify-start items-center text-wrapper w-full" open-type="chooseAvatar"
        @chooseavatar="onChooseavatar" @click="getUserProfileByWx" v-if="!showPhoneBtn">
        <text class="text">获取用户头像</text>
      </button>

      <!-- 第二步：获取手机号 -->
      <button v-if="showPhoneBtn" class="mt-24 flex-col justify-start items-center text-wrapper w-full"
        open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
        <text class="text">获取手机号</text>
      </button>
      <!-- <button class="mt-24 flex-col justify-start items-center text-wrapper" @click="handleLogin">
        <text class="text">登录/注册</text>
      </button> -->
      <!-- 用户协议 -->
      <view class="agreement-section">
        <view class="agreement-item">
          <view class="checkbox" :class="{ checked: agreed }" @tap="toggleAgreement">
            <text v-if="agreed" class="checkmark">✓</text>
          </view>
          <view class="agreement-text">
            <text @tap="toggleAgreement">我已阅读并同意</text>
            <text class="link" @tap="showAgreementPopup">《用户协议》</text>
            <text @tap="toggleAgreement">和</text>
            <text class="link" @tap="showPrivacyPopup">《隐私政策》</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 用户协议弹出层 -->
    <uni-popup ref="agreementPopup" type="bottom" :safe-area="true">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">用户协议</text>
          <view class="close-btn" @tap="closeAgreementPopup">
            <text class="close-icon">×</text>
          </view>
        </view>
        <scroll-view class="popup-body" scroll-y="true">
          <view v-if="loading" class="loading-content">
            <text>加载中...</text>
          </view>
          <view v-else-if="error" class="error-content">
            <text>{{ error }}</text>
            <button @tap="getUserAgreement" class="retry-btn">重试</button>
          </view>
          <MpHtmlWrapper v-else :content="htmlContent" :max-length="8000" @load="onMpHtmlLoad('useragreement')"
            @error="onMpHtmlError('useragreement')" />
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 隐私政策弹出层 -->
    <uni-popup ref="privacyPopup" type="bottom" :safe-area="true">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">隐私政策</text>
          <view class="close-btn" @tap="closePrivacyPopup">
            <text class="close-icon">×</text>
          </view>
        </view>
        <scroll-view class="popup-body" scroll-y="true">
          <view v-if="loading" class="loading-content">
            <text>加载中...</text>
          </view>
          <view v-else-if="error" class="error-content">
            <text>{{ error }}</text>
            <button @tap="getPrivacyPopup" class="retry-btn">重试</button>
          </view>
          <MpHtmlWrapper v-else :content="privacyContent" :max-length="8000" @load="onMpHtmlLoad('privacyagreement')"
            @error="onMpHtmlError('privacyagreement')" />
        </scroll-view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
  import { ref } from 'vue'
  import { onShow } from '@dcloudio/uni-app'
  import { imgUrl } from '@/utils/config'
  import { useRequest } from '@/api';
  import MpHtmlWrapper from '@/components/MpHtmlWrapper/MpHtmlWrapper.vue'

  const { API_LOGIN_WX_POST, API_LOGIN_MOBILE_POST, API_GET_USER_AGREEMENT, API_GET_PRIVACY_AGREEMENT, API_GET_USER_PROFILE_POST, API_MEMBER_GET_USER_INFO_POST, API_GET_USER_PHONE_POST } = useRequest()

  // 显示手机号按钮
  const showPhoneBtn = ref(false)
  // 用户头像和昵称信息
  const userProfile = ref({})
  // 登陆成功跳转页面
  const redirectUrl = ref('/pages/leagueMatchesHome/index')
  const htmlContent = ref('')
  const privacyContent = ref('')
  const agreed = ref(false)
  const loading = ref(false)
  const error = ref('')
  const wxCode = ref('')
  const avatarUrl = ref('')
  const iv = ref('')
  const encryptedData = ref('')
  const userProfileParams = ref({
    code: '',
    cloudID: '',
    iv: '',
    encryptedData: '',
    userInfo: {},
    signature: '',
    phone: ''
  })
  console.log('imgUrl', imgUrl);

  // 弹出层引用
  const agreementPopup = ref(null)
  const privacyPopup = ref(null)

  function toggleAgreement() {
    agreed.value = !agreed.value
  }

  // 显示用户协议弹出层
  const showAgreementPopup = () => {
    if (!htmlContent.value) {
      getUserAgreement()
    }
    agreementPopup.value.open()
  }

  // 关闭用户协议弹出层
  const closeAgreementPopup = () => {
    agreementPopup.value.close()
  }

  // 显示隐私政策弹出层
  const showPrivacyPopup = () => {
    if (!privacyContent.value) {
      getPrivacyPopup()
    }
    privacyPopup.value.open()
  }

  // 关闭隐私政策弹出层
  const closePrivacyPopup = () => {
    privacyPopup.value.close()
  }
  // 获取手机号回调
  const getPhoneNumber = async (e) => {
    console.log('getPhoneNumber', e);
    if (!agreed.value) {
      uni.showToast({
        title: '请先勾选用户协议',
        icon: 'none'
      })
      return
    }
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      // 获取手机号成功，执行登录
      console.log(1111111111111111111);
      // debugger
      // await doLogin(e.detail)
      getPhoneNumberByWx(e.detail.code)
    } else if (e.detail.errMsg === 'getPhoneNumber:fail' || e.detail.errMsg === 'getPhoneNumber:fail user deny') {
      // 统一隐藏按钮，显示微信一键登录
      showPhoneBtn.value = false

      // 提示用户可以重新点击微信一键登录
      uni.showToast({
        title: '已取消，您可以重新点击微信一键登录',
        icon: 'none'
      })

      if (e.detail.errMsg.includes('用户绑定的手机需要进行验证')) {
        uni.showModal({
          title: '手机号验证',
          content: '您的微信账号绑定的手机号需要重新验证，请在微信中完成手机号验证后再试',
          showCancel: false,
          confirmText: '我知道了'
        })
      } else {
        // 可选：将具体错误信息展示给用户，便于排查
        uni.showToast({
          title: `获取手机号失败: ${e.detail.errMsg.replace('getPhoneNumber:fail ', '')}`,
          icon: 'none'
        })
      }
    }
  }
  // 获取用户头像：上传成功后再调用 getUserProfile
  const onChooseavatar = async (e) => {
    // console.log('onChooseavatar', e.detail?.avatarUrl)
    // if (!agreed.value) {
    //   uni.showToast({ title: '请先勾选用户协议', icon: 'none' })
    //   return
    // }
    // showPhoneBtn.value = false
    // let avatarUrlTemp = ''
    // try {
    //   uni.showLoading({ title: '上传中...' })
    //   if (e.detail?.avatarUrl) {
    //     avatarUrlTemp = await uploadFile(e.detail.avatarUrl)
    //     console.log('avatarUrlTemp', avatarUrlTemp)
    //   }
    //   if (!avatarUrlTemp) {
    //     uni.showToast({ title: '上传失败，请重试', icon: 'none' })
    //     return
    //   }
    //   console.log('avatarUrlTemp>>>>>>>>++++>>>>>>>>>>', avatarUrlTemp)
    //   await getUserProfile(avatarUrlTemp)
    // } catch (err) {
    //   console.error('onChooseavatar error', err)
    //   uni.showToast({ title: '上传失败', icon: 'none' })
    // } finally {
    //   uni.hideLoading()
    // }
    if (!agreed.value) return uni.showToast({ title: '请先勾选用户协议', icon: 'none' })
    const local = e?.detail?.avatarUrl
    if (!local) return uni.showToast({ title: '头像选择失败', icon: 'none' })

    // uni.showLoading({ title: '上传中...' })
    const url = await uploadFile(local)      // 必须返回公网 URL
    uni.hideLoading()
    if (!url) return uni.showToast({ title: '头像选择失败，请重试', icon: 'none' })

    await getUserProfile(url)
  }
  const uploadFile = async (filePath) => {
    const res = await new Promise((resolve, reject) => {
      uni.uploadFile({
        url: `${import.meta.env.VITE_APP_API_BASEURL}/api/index/upload`,
        filePath, name: 'file',
        header: { Authorization: uni.getStorageSync('token') },
        success: r => { try { resolve(JSON.parse(r.data)) } catch { resolve(r) } },
        fail: reject
      })
    })
    if (res?.code === 1) {
      const url = res.data?.fullurl || res.data?.url || ''
      if (url) { userProfile.value.avatarUrl = url; uni.setStorageSync('avatarUrl', url); return url }
    }
    return ''
  }
  //登陆第一步，获取用户头像和昵称
  const getUserProfileByWx = () => {
    showPhoneBtn.value = false;
    uni.getUserProfile({
      desc: '获取用户头像和昵称',
      success: (res) => {
        console.log('getUserProfileByWx success', res);
        // 保存用户信息
        userProfile.value = res.userInfo
        userProfileParams.value.cloudID = res.cloudID
        userProfileParams.value.iv = res.iv
        userProfileParams.value.encryptedData = res.encryptedData
        userProfileParams.value.signature = res.signature
        console.log('userProfileParams', userProfileParams.value);
        // getUserProfile(userProfileParams);//调接口获取用户信息
      },
      fail: (err) => {
        console.log('getUserProfileByWx fail', err);
        // 如果获取用户信息失败，使用默认信息进行登录
      }
    })
  }

  // // 执行登录
  // const doLogin = async (phoneData) => {
  //   try {
  //     uni.showLoading({
  //       title: '登录中...'
  //     });

  //     console.log('开始登录，参数:', {
  //       code: userProfileParams.value.code,
  //       phoneCode: phoneData.code,
  //       encryptedData: phoneData.encryptedData,
  //       iv: phoneData.iv,
  //       nickname: userProfile.value.nickName || `微信用户${Math.random().toString(36).substring(2, 15)}`,
  //       avatar: userProfile.value.avatarUrl
  //     })

  //     // 调用登录接口
  //     const res = await API_LOGIN_WX_POST({
  //       code: userProfileParams.value.code,
  //       phoneCode: phoneData.code,
  //       encryptedData: phoneData.encryptedData,
  //       iv: phoneData.iv,
  //       nickname: userProfile.value.nickName || `微信用户${Math.random().toString(36).substring(2, 15)}`,
  //       avatar: userProfile.value.avatarUrl
  //     })

  //     console.log('登录接口返回:', res)

  //     if (res.code === 1) {
  //       // 登录成功
  //       uni.setStorageSync('token', res.data.token);
  //       uni.setStorageSync('userInfo', res.data.userinfo);

  //       uni.showToast({
  //         title: '登录成功',
  //         icon: 'success'
  //       });

  //       // 延迟跳转
  //       setTimeout(() => {
  //         uni.reLaunch({
  //           url: redirectUrl.value
  //         })
  //       }, 1500);

  //     } else {
  //       throw new Error(res.msg || '登录失败');
  //     }
  //   } catch (error) {
  //     console.error('登录失败:', error);
  //     uni.showToast({
  //       title: error.message || '登录失败，请重试',
  //       icon: 'none'
  //     });
  //   } finally {
  //     uni.hideLoading();
  //   }
  // }

  // 获取用户协议
  const getUserAgreement = async () => {
    try {
      loading.value = true
      error.value = ''

      const res = await API_GET_USER_AGREEMENT()
      console.log('getUserAgreement', res)

      if (res.code === 1) {
        htmlContent.value = res.data.useragreement
      } else {
        error.value = res.msg || '获取用户协议失败'
        uni.showToast({ title: res.msg, icon: 'none' })
      }
    } catch (error) {
      console.error('获取用户协议失败:', error)
      error.value = '网络错误'
      uni.showToast({ title: '网络错误', icon: 'none' })
    } finally {
      loading.value = false
    }
  }

  const onMpHtmlLoad = (type) => {
    if (type === 'useragreement') {
      console.log('用户协议加载成功')
    } else if (type === 'privacyagreement') {
      console.log('隐私政策加载成功')
    }
    error.value = ''
  }

  const onMpHtmlError = (type, err) => {
    if (type === 'useragreement') {
      console.error('用户协议渲染失败:', err)
    } else if (type === 'privacyagreement') {
      console.error('隐私政策渲染失败:', err)
    }
    error.value = '内容渲染失败，请重试'
  }
  // 获取隐私政策
  const getPrivacyPopup = async () => {
    try {
      loading.value = true
      error.value = ''

      const res = await API_GET_PRIVACY_AGREEMENT()
      console.log('getPrivacyPopup', res)

      if (res.code === 1) {
        privacyContent.value = res.data.privacyagreement
      } else {
        error.value = res.msg || '获取隐私政策失败'
        uni.showToast({ title: res.msg, icon: 'none' })
      }
    } catch (error) {
      console.error('获取隐私政策失败:', error)
      error.value = '网络错误'
      uni.showToast({ title: '网络错误', icon: 'none' })
    } finally {
      loading.value = false
    }
  }
  onShow(() => {
  })

  // const loginByMobile = async (code) => {
  //   console.log('loginByMobile', code,);
  //   try {
  //     // 显示加载提示
  //     uni.showLoading({
  //       title: '登录中...'
  //     });

  //     const res = await API_LOGIN_WX_POST({
  //       code
  //     })
  //     console.log('loginByMobileres', res);

  //     // 隐藏加载提示
  //     uni.hideLoading();

  //     if (res.code === 1) {
  //       console.log('loginByMobileres.data', res);

  //       uni.setStorageSync('token', res.data.token);
  //       uni.setStorageSync('userInfo', res.data.userinfo);
  //       if (res.data.token && userProfileParams.value.iv && userProfileParams.value.encryptedData) {
  //         getUserProfile();//获取用户信息
  //       }
  //       // if (res.data.token && userProfileParams.value.phone) {
  //       // handleLogin();
  //       // }


  //     } else {
  //       throw new Error(res.msg || '登录失败');
  //     }
  //   } catch (error) {
  //     console.error('登录失败:', error);
  //     uni.hideLoading();
  //     uni.showToast({
  //       title: error.message || '登录失败，请重试',
  //       icon: 'none'
  //     });
  //   }
  // }
  const getUserProfile = async (avatarUrlTemp) => {
    let params = {
      iv: userProfileParams.value.iv,
      encryptedData: userProfileParams.value.encryptedData,
      nickname: userProfile.value.nickName,
      avatar: avatarUrlTemp,
      gender: userProfile.value.gender,
    }
    showPhoneBtn.value = false;
    userProfileParams.value.userInfo = {};
    const res = await API_MEMBER_GET_USER_INFO_POST(params)
    console.log('getUserProfile>>>>>>', res);
    if (res.code === 1) {
      userProfileParams.value.userInfo = res.data;
      uni.setStorageSync('userInfo', res.data);
      if (res.data.mobile) {
        uni.setStorageSync('phone', res.data.mobile);
        showPhoneBtn.value = false;
        //返回上一层
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } else {
        showPhoneBtn.value = true;
      }
    } else {
      console.log('getUserProfile fail', res);
    }

  }
  const getPhoneNumberByWx = async (code) => {
    let params = {
      code
    }
    userProfileParams.value.phone = '';
    const res = await API_GET_USER_PHONE_POST(params)
    console.log('getPhoneNumberByWx>>>>>>', res);
    if (res.code === 1) {
      userProfileParams.value.phone = res.data.mobile;
      uni.setStorageSync('phone', res.data.mobile);
      // 显示成功提示
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      });
      //返回上一层
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    } else {
      console.log('getPhoneNumberByWx fail', res);
    }
  }
  // const handleLogin = () => {
  //   // 显示成功提示
  //   uni.showToast({
  //     title: '登录成功',
  //     icon: 'success'
  //   });

  //   console.log('redirectUrl', redirectUrl.value);

  //   // 延迟跳转，让用户看到成功提示
  //   setTimeout(() => {
  //     if (redirectUrl.value && redirectUrl.value !== "undefined") {
  //       uni.redirectTo({
  //         url: redirectUrl.value
  //       })
  //     } else {
  //       uni.reLaunch({
  //         url: '/pages/leagueMatchesHome/index'
  //       })
  //     }
  //   }, 1500);
  // }


  // // 获取用户头像
  // const getUserAvatar = () => {
  //   uni.getUserProfile({
  //     desc: '获取用户头像',
  //     success: (res) => {
  //       console.log(res)
  //     }
  //   })
  // }
  // const handleLogin = () => {
  //   uni.navigateTo({
  //     url: '/pages/login/mobileLogin'
  //   })
  // }
</script>

<style scoped lang="scss">
  .login-page {
    &.page {
      padding-bottom: 524rpx;
      background-color: #ffffff;
      width: 100%;
      overflow-y: auto;
      overflow-x: hidden;
      height: 100vh;

      .image {
        filter: drop-shadow(0rpx 2rpx 0rpx #4444441a);
        width: 100vw;
        height: 23.4667vw;
      }

      .image-wrapper {
        margin-top: 264rpx;
        padding: 12rpx 0 12rpx;
        background-position: 0% 0%;
        background-size: 100% 100%;
        background-repeat: no-repeat;
        width: 263rpx;

        .image_2 {
          width: 236rpx;
        }
      }

      .group {
        margin-top: 184rpx;
        padding: 0 80rpx;

        .image_3 {
          width: 590rpx;
          height: 88rpx;
        }

        .w-full {
          background-color: #1D428A !important;

          .text {
            color: #ffffff !important;
          }
        }

        .text-wrapper {
          padding: 20rpx 0;
          width: 590rpx;
          height: 90rpx;
          background-color: #4444441a;
          box-shadow: 0rpx 0rpx 18rpx 0rpx #ee73500a;
          border-radius: 44rpx;
          border: unset !important;

          &::after {
            border: unset !important;
          }

          .text {
            color: #444444;
            font-size: 36rpx;
            font-family: 'PingFang SC';
            line-height: 50rpx;
          }
        }

        .agreement-section {
          padding-bottom: 60rpx;
          padding-top: 60rpx;

          .agreement-item {
            display: flex;
            align-items: flex-start;
            padding: 0 20rpx;

            .checkbox {
              width: 32rpx;
              height: 32rpx;
              border: 2rpx solid #ddd;
              border-radius: 6rpx;
              margin-right: 16rpx;
              margin-top: 4rpx;
              display: flex;
              align-items: center;
              justify-content: center;
              background: #fff;

              &.checked {
                background: #1a73e8;
                border-color: #1a73e8;
              }

              .checkmark {
                color: #fff;
                font-size: 20rpx;
                font-weight: bold;
              }
            }

            .agreement-text {
              flex: 1;
              font-size: 26rpx;
              color: #666;
              line-height: 1.5;

              .link {
                color: #1a73e8;
              }
            }
          }
        }
      }
    }
  }

  /* 弹出层样式 */
  .popup-content {
    background: #fff;
    border-radius: 24rpx 24rpx 0 0;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
  }

  .popup-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx 32rpx 24rpx;
    border-bottom: 1rpx solid #f0f0f0;
    position: sticky;
    top: 0;
    background: #fff;
    z-index: 10;

    .popup-title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }

    .close-btn {
      width: 48rpx;
      height: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      background: #f5f5f5;

      .close-icon {
        font-size: 32rpx;
        color: #666;
        font-weight: bold;
      }
    }
  }

  .popup-body {
    flex: 1;
    padding: 24rpx 24rpx 32rpx 24rpx;
    max-height: calc(80vh - 120rpx);
    width: fit-content;
  }

  .loading-content,
  .error-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 200rpx;
    color: #666;
    font-size: 28rpx;

    .retry-btn {
      margin-top: 24rpx;
      padding: 16rpx 32rpx;
      background: #007aff;
      color: #fff;
      border-radius: 8rpx;
      font-size: 28rpx;
    }
  }

  .privacy-content {
    .privacy-text {
      font-size: 28rpx;
      line-height: 1.6;
      color: #333;
      white-space: pre-wrap;
    }
  }
</style>